package com.example.smartagrisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartagrisys.entity.Transaction;
import com.example.smartagrisys.mapper.TransactionMapper;
import com.example.smartagrisys.service.TransactionService;
import com.example.smartagrisys.vo.TransactionStatsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 交易记录服务实现类
 */
@Slf4j
@Service
public class TransactionServiceImpl extends ServiceImpl<TransactionMapper, Transaction> implements TransactionService {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public List<Transaction> getUserTransactions(Long userId) {
        if (userId == null) {
            log.error("获取交易记录时用户ID为空");
            return null;
        }
        
        LambdaQueryWrapper<Transaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Transaction::getUserId, userId);
        wrapper.orderByDesc(Transaction::getTransactionDate);
        
        return list(wrapper);
    }

    @Override
    public boolean createTransaction(Transaction transaction) {
        if (transaction == null) {
            log.error("创建交易记录时参数为空");
            return false;
        }
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        transaction.setCreateTime(now);
        transaction.setUpdateTime(now);
        
        return save(transaction);
    }

    @Override
    public List<Transaction> getTransactionsByDateRange(Long userId, String startDate, String endDate) {
        if (userId == null) {
            log.error("获取交易记录时用户ID为空");
            return null;
        }
        
        LambdaQueryWrapper<Transaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Transaction::getUserId, userId);
        
        // 如果有日期范围，添加日期过滤条件
        if (startDate != null && endDate != null) {
            LocalDateTime startDateTime = LocalDate.parse(startDate, DATE_FORMATTER).atStartOfDay();
            LocalDateTime endDateTime = LocalDate.parse(endDate, DATE_FORMATTER).atTime(LocalTime.MAX);
            
            wrapper.between(Transaction::getTransactionDate, startDateTime, endDateTime);
        }
        
        wrapper.orderByDesc(Transaction::getTransactionDate);
        
        return list(wrapper);
    }

    @Override
    public double getUserIncomeTotal(Long userId) {
        if (userId == null) {
            log.error("获取用户收入总额时用户ID为空");
            return 0;
        }
        
        LambdaQueryWrapper<Transaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Transaction::getUserId, userId)
               .eq(Transaction::getType, "income");
        
        // 获取所有收入交易记录
        List<Transaction> incomeTransactions = list(wrapper);
        
        // 计算总额
        BigDecimal total = incomeTransactions.stream()
                .map(Transaction::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        return total.doubleValue();
    }

    @Override
    public double getUserExpenseTotal(Long userId) {
        if (userId == null) {
            log.error("获取用户支出总额时用户ID为空");
            return 0;
        }
        
        LambdaQueryWrapper<Transaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Transaction::getUserId, userId)
               .eq(Transaction::getType, "expense");
        
        // 获取所有支出交易记录
        List<Transaction> expenseTransactions = list(wrapper);
        
        // 计算总额
        BigDecimal total = expenseTransactions.stream()
                .map(Transaction::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        return total.doubleValue();
    }

    /**
     * 检查订单编号是否已存在交易记录
     *
     * @param orderNumber 订单编号
     * @return 是否存在
     */
    @Override
    public boolean existsByOrderNumber(String orderNumber) {
        if (!StringUtils.hasText(orderNumber)) {
            return false;
        }
        
        LambdaQueryWrapper<Transaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Transaction::getOrderNumber, orderNumber);
        return this.count(wrapper) > 0;
    }
    
    /**
     * 获取用户的交易统计数据
     *
     * @param userId 用户ID
     * @return 交易统计数据
     */
    @Override
    public TransactionStatsVO getTransactionStatsByUserId(Long userId) {
        TransactionStatsVO statsVO = new TransactionStatsVO();
        
        // 获取收入总额
        double incomeTotal = getUserIncomeTotal(userId);
        
        // 获取支出总额
        double expenseTotal = getUserExpenseTotal(userId);
        
        // 计算净收入
        double netIncome = incomeTotal - expenseTotal;
        
        statsVO.setIncomeTotal(incomeTotal);
        statsVO.setExpenseTotal(expenseTotal);
        statsVO.setNetIncome(netIncome);
        
        return statsVO;
    }
    
    /**
     * 根据用户ID获取交易记录
     *
     * @param userId    用户ID
     * @param startDate 开始日期（可选）
     * @param endDate   结束日期（可选）
     * @return 交易记录列表
     */
    @Override
    public List<Transaction> getTransactionsByUserId(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        LambdaQueryWrapper<Transaction> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Transaction::getUserId, userId);
        
        // 添加日期范围条件
        if (startDate != null) {
            wrapper.ge(Transaction::getTransactionDate, startDate);
        }
        
        if (endDate != null) {
            wrapper.le(Transaction::getTransactionDate, endDate);
        }
        
        // 按交易日期降序排序
        wrapper.orderByDesc(Transaction::getTransactionDate);
        
        return this.list(wrapper);
    }
} 